package com.sctvcloud.qingchuan.ui.dialog;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetDialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.blankj.utilcode.util.ToastUtils;
import com.canyinghao.canrefresh.CanRefreshLayout;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.utils.ListUtils;
import com.sctvcloud.qingchuan.R;
import com.sctvcloud.qingchuan.application.Constances;
import com.sctvcloud.qingchuan.beans.FComment;
import com.sctvcloud.qingchuan.beans.FNews;
import com.sctvcloud.qingchuan.http.AbsListNetCallback;
import com.sctvcloud.qingchuan.http.AbsNetCallBack;
import com.sctvcloud.qingchuan.http.NetUtils;
import com.sctvcloud.qingchuan.ui.adapter.CommentAdapter;
import com.sctvcloud.qingchuan.utils.ListTypeUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 短视频底部评论弹框
 *
 * @author suming
 * @date 2020/8/13 17:21
 */
public class BottomCommentDialogFragment extends BottomSheetDialogFragment implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener,
        OnItemInternalClick, CommentDiaFragment.SendComment {
    private static final String TAG = BottomCommentDialogFragment.class.getSimpleName();
    private static final String KEY_URL = "url";

    @BindView(R.id.comment_refresh)
    CanRefreshLayout refreshLayout;
    @BindView(R.id.can_content_view)
    RecyclerView recyclerView;

    private CommentAdapter mAdapter;

    private String mNewsUrl;
    private int mIndexNumber = 0;
    private String mNewsId;

    /**
     * @param url 新闻地址
     * @return {@link BottomCommentDialogFragment}
     */
    public static BottomCommentDialogFragment newInstance(String url) {
        Bundle args = new Bundle();
        args.putString(KEY_URL, url);
        BottomCommentDialogFragment fragment = new BottomCommentDialogFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mNewsUrl = getArguments().getString(KEY_URL);
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.dialog_bottom_comment, container, false);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        mAdapter = new CommentAdapter(getContext(), new ArrayList<FComment>());
        mAdapter.setItemInternalClick(this);
        recyclerView.setAdapter(mAdapter);

        if (!TextUtils.isEmpty(mNewsUrl)) {
            getNewsDetails(mNewsUrl);
        }
    }

    @OnClick({R.id.comment})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.comment:
                if (TextUtils.isEmpty(mNewsId)) return;
                showCommentDialog(mNewsId, null);  // 0代表新闻评论
                break;
        }
    }


    private void getNewsDetails(String url) {
        NetUtils.getNetAdapter().getNewsInfo(TAG, url, new AbsNetCallBack<FNews>(FNews.class) {
            @Override
            public void onSuc(FNews datas) {
                if (datas != null) {
                    mNewsId = datas.getNewsId();
                    mIndexNumber = 0;
                    getComments(mIndexNumber);
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg, int netCode) {
                super.onError(ex, errorMsg, netCode);
            }

            @Override
            public void onEnd() {
                super.onEnd();
            }
        });
    }

    private void getComments(final int index) {
        if (TextUtils.isEmpty(mNewsId)) return;
        NetUtils.getNetAdapter().getCommentList(TAG, mNewsId, Constances.REQUEST_COMMENT_TYPE_NEWS, 20, index, new AbsListNetCallback<FComment>(ListTypeUtils.FProgramme()) {

            @Override
            public void onSuc(List<FComment> comments) {
                mIndexNumber += 1;
                int count = getPageResponse().getData().getCommentCount();
                if (ListUtils.isListValued(comments)) {
                    List<FComment> data = dataHandle(comments);
                    if (index == 0) {
                        mAdapter.setData(data);
                    } else {
                        mAdapter.addDatas(data);
                    }
                }

            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
            }

            @Override
            public void onEnd() {
                super.onEnd();
            }
        });
    }

    private List<FComment> dataHandle(List<FComment> datas) {
        List<FComment> comments = new ArrayList<>();
        List<FComment> answers = new ArrayList<>();
        if (null != datas) {
            FComment comment;
            for (int i = 0; i < datas.size(); i++) {
                comment = datas.get(i);
                if (TextUtils.isEmpty(comment.getAnswerTo())) {
                    comments.add(comment);
                } else {
                    answers.add(comment);
                }
            }

            for (int j = 0; j < answers.size(); j++) {
                FComment co = answers.get(j);
                for (int k = 0; k < comments.size(); k++) {
                    if (!TextUtils.isEmpty(co.getAnswerToCommentId()) && co.getAnswerToCommentId().equalsIgnoreCase(comments.get(k).getCommentId())) {
                        comments.add(k + 1, co);
                        break;
                    }
                }
            }
        }
        return comments;
    }

    @Override
    public void onRefresh() {
        mIndexNumber = 0;
        getComments(mIndexNumber);
    }

    @Override
    public void onLoadMore() {
        getComments(mIndexNumber);
    }

    @Override
    public void onItemInternalClick(View itemView, View view, int position) {
        FComment comment = mAdapter.getItem(position);
        if (!TextUtils.isEmpty(comment.getCommentId())) {
            showCommentDialog(mNewsId, comment.getCommentId());
        } else {
            ToastUtils.showShort("评论id为空");
        }
    }


    private void showCommentDialog(String newsId, String commentId) {
        if (TextUtils.isEmpty(newsId)) {
            return;
        }
        FragmentManager fm = getChildFragmentManager();
        CommentDiaFragment commentDiaFragment = new CommentDiaFragment();
        commentDiaFragment.setSendComment(this);
        commentDiaFragment.setCommentType(Constances.COMMENT_TYPE_NEWS);
        commentDiaFragment.setTypes(Constances.COMMENT_TYPE_NEWS);
        commentDiaFragment.setInfo(newsId, commentId);
        commentDiaFragment.show(fm, "CommentDiaFragment");
        fm.executePendingTransactions();
    }

    @Override
    public boolean onCommentSendPrepare(int mode) {
        return true;
    }

    @Override
    public void onCommentSendSuccess(int mode) {
        onRefresh();
    }

    @Override
    public void onCommentSendFinish(int mode, boolean isNetSuc) {

    }
}
